package com.sxz.mall.coupon.service.impl;

import com.sxz.mall.coupon.entity.SeckillSkuRelationEntity;
import com.sxz.mall.coupon.service.SeckillSkuRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxz.mall.common.utils.PageUtils;
import com.sxz.mall.common.utils.Query;

import com.sxz.mall.coupon.dao.SeckillSessionDao;
import com.sxz.mall.coupon.entity.SeckillSessionEntity;
import com.sxz.mall.coupon.service.SeckillSessionService;


@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {

    @Autowired
    private SeckillSkuRelationService relationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<SeckillSessionEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SeckillSessionEntity> getLatests2Days() {
        List<SeckillSessionEntity> list = this.list(new QueryWrapper<SeckillSessionEntity>().
                between("start-time", startTime(), endTime()));

        List<SeckillSessionEntity> newList = list.stream().map((item) -> {
            List<SeckillSkuRelationEntity> relationEntities = relationService.
                    list(new QueryWrapper<SeckillSkuRelationEntity>().
                            eq("promotion_session_id", item.getId()));
            item.setRelationEntities(relationEntities);
            return item;
        }).collect(Collectors.toList());

        return newList;
    }

    private String startTime() {
        LocalDate now = LocalDate.now(); // 今天
        LocalDate startDay = now.plusDays(1); // 明天 日期
        // 明日最早时间，需要格式化
        LocalDateTime startTime = LocalDateTime.of(startDay, LocalTime.MIN);
        return startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    private String endTime() {
        LocalDate now = LocalDate.now(); // 今天
        LocalDate endtDay = now.plusDays(2); // 后天 日期
        // 明日最早时间，需要格式化
        LocalDateTime endTime = LocalDateTime.of(endtDay, LocalTime.MAX);
        return endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

}